import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/src/provider.dart';
import 'package:wkweb/entities/banner_entity.dart';
import 'package:wkweb/entities/wk_response.dart';
import 'package:wkweb/models/allmodels.dart';
import 'package:wkweb/net/api.dart';
import 'package:wkweb/net/http_manager.dart';
import 'package:wkweb/util/route_paths.dart';
import 'package:wkweb/util/utils.dart';
import 'package:wkweb/view/state_layout.dart';

class WkBanner extends StatefulWidget {
  const WkBanner({Key? key}) : super(key: key);

  @override
  _WkBannerState createState() => _WkBannerState();
}

class _WkBannerState extends State<WkBanner> {
  PageController? _bannerController;
  int _bannerCurrentIndex = 1;
  List<BannerEntity> _bannerData = <BannerEntity>[];
  int _bannerLoadState = StateLayout.stateLoading;
  Timer? _bannerTimer;

  @override
  void initState() {
    super.initState();
    _bannerController =
        PageController(viewportFraction: 0.9, initialPage: _bannerCurrentIndex);

    _loadBanner();
    _createTimer();
  }

  @override
  void dispose() {
    _bannerTimer?.cancel();
    _bannerTimer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = _bannerData
        .map<Widget>(
          (BannerEntity entity) => Padding(
            padding: EdgeInsets.all(10),
            child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: InkWell(
                  onTap: () => _onBannerClick(entity),
                  child: Image.network(
                    entity.imagePath ?? "",
                    fit: BoxFit.cover,
                    cacheHeight: 200,
                    cacheWidth: 360,
                    key: Key(entity.id.toString()),
                    loadingBuilder: (
                      BuildContext context,
                      Widget child,
                      ImageChunkEvent? loadingProgress,
                    ) {
                      if (loadingProgress == null) {
                        return child;
                      }
                      return Center(
                        child: CupertinoActivityIndicator(
                          radius: 20,
                        ),
                      );
                    },
                  ),
                )),
          ),
        )
        .toList();
    return StateLayout(
        successWidget: PageView.builder(
            controller: _bannerController,
            itemCount: children.length * 3,
            itemBuilder: (BuildContext context, int index) {
              return children[index % (children.length)];
            }),
        state: _bannerLoadState);
  }

  //加载banner数据
  _loadBanner() {
    String url = getBannerUrl();
    HttpManager.getData(url, success: (result) {
      WkResp resp = WkResp.fromJson(result);
      List<BannerEntity> tmp = <BannerEntity>[];
      if (resp.data != null) {
        resp.data.forEach((json) => {tmp.add(BannerEntity.fromJson(json))});
      }
      setState(() {
        _bannerData = tmp;
        _bannerLoadState = StateLayout.stateSuccess;
      });
    }, fail: (e) {
      Utils.showTextSnack(context, "Banner 加载失败！请重试! ${e.toString()}");
      setState(() {
        _bannerLoadState = StateLayout.stateError;
      });
    });
  }

  void _createTimer() {
    Timer.periodic(Duration(seconds: 2), (timer) {
      if (context.read<TabModel>().currentIndex != 0) {
        return;
      }
      int index = _bannerCurrentIndex;
      if (_bannerCurrentIndex >= _bannerData.length * 2) {
        index = _bannerCurrentIndex % (_bannerData.length);
        _bannerController?.jumpToPage(index);
      }
      _bannerController?.animateToPage(index + 1,
          duration: Duration(milliseconds: 500), curve: Curves.ease);
      setState(() {
        _bannerTimer = timer;
        _bannerCurrentIndex = index + 1;
      });
    });
  }

  ///点击Banner图
  _onBannerClick(BannerEntity entity) {
    Navigator.of(context)
        .pushNamed(RoutePaths.pathWebPage, arguments: entity.url ?? "");
  }
}
